<template>
  <view>
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title"></view>
        <view class="uni-sub-title"></view>
      </view>
      <view class="uni-group">
        <button
          class="uni-button"
          type="default"
          size="mini"
          @click="navigateTo('./add')"
        >
          新增
        </button>
        <button
          class="uni-button"
          type="default"
          size="mini"
          :disabled="!selectedIndexs.length"
          @click="delTable"
        >
          批量删除
        </button>
        <download-excel
          class="hide-on-phone"
          :fields="exportExcel.fields"
          :data="exportExcelData"
          :type="exportExcel.type"
          :name="exportExcel.filename"
        >
          <button class="uni-button" type="primary" size="mini">
            导出 Excel
          </button>
        </download-excel>
      </view>
    </view>
    <view class="uni-container">
      <unicloud-db
        ref="udb"
        :collection="collectionList"
        :where="where"
        page-data="replace"
        :orderby="orderby"
        :getcount="true"
        :page-size="options.pageSize"
        :page-current="options.pageCurrent"
        v-slot:default="{ data, pagination, loading, error, options }"
        :options="options"
        loadtime="manual"
        @load="onqueryload"
      >
        <uni-table
          ref="table"
          :loading="loading"
          :emptyText="error.message || '没有更多数据'"
          border
          stripe
          type="selection"
          @selection-change="selectionChange"
        >
          <uni-tr>
            <uni-th align="center">活动分类</uni-th>
            <uni-th
              align="center"
              filter-type="search"
              @filter-change="filterChange($event, 'category_id')"
              >所属活动</uni-th
            >
            <uni-th
              align="center"
              sortable
              v-if="isSuperAdmin"
              @sort-change="sortChange($event, 'user_id')"
              >user_id</uni-th
            >
            <uni-th
              align="center"
              filter-type="search"
              @filter-change="filterChange($event, 'name')"
              sortable
              @sort-change="sortChange($event, 'name')"
              >优惠券名称</uni-th
            >
            <uni-th
              align="center"
              filter-type="range"
              @filter-change="filterChange($event, 'discount')"
              sortable
              @sort-change="sortChange($event, 'discount')"
              >折扣率</uni-th
            >
            <uni-th
              align="center"
              filter-type="search"
              @filter-change="filterChange($event, 'validity')"
              sortable
              @sort-change="sortChange($event, 'validity')"
              >有效期</uni-th
            >
            <uni-th
              align="center"
              filter-type="select"
              :filter-data="options.filterData.status_localdata"
              @filter-change="filterChange($event, 'status')"
              >优惠券状态</uni-th
            >
            <uni-th
              align="center"
              filter-type="search"
              @filter-change="filterChange($event, 'customImage')"
              sortable
              @sort-change="sortChange($event, 'customImage')"
              >自定义图片</uni-th
            >
            <uni-th align="center">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item, index) in data" :key="index">
            <!-- 分类 -->
            <uni-td align="center">
              {{ getCategoryName(item) }}
            </uni-td>
            <!-- 所属活动 -->
            <uni-td align="center">{{
              item.category_id &&
              item.category_id[0] &&
              item.category_id[0].text
            }}</uni-td>
            <!-- 优惠券名称 -->
            <uni-td align="center" v-if="isSuperAdmin">{{
              item.user_id
            }}</uni-td>
            <uni-td align="center">{{ item.name }}</uni-td>
            <uni-td align="center">{{ item.discount }}</uni-td>
            <uni-td align="center">
              <uni-dateformat
                :threshold="[0, 0]"
                :date="item.validity"
              ></uni-dateformat>
            </uni-td>
            <uni-td align="center">{{
              options.status_valuetotext[item.status]
            }}</uni-td>
            <uni-td align="center">略</uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <button
                  @click="navigateTo('./edit?id=' + item._id, false)"
                  class="uni-button"
                  size="mini"
                  type="primary"
                >
                  修改/详情
                </button>
                <button
                  @click="confirmDelete(item._id)"
                  class="uni-button"
                  size="mini"
                  type="warn"
                >
                  删除
                </button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box">
          <uni-pagination
            show-icon
            :page-size="pagination.size"
            v-model="pagination.current"
            :total="pagination.count"
            @change="onPageChanged"
          />
        </view>
      </unicloud-db>
    </view>
  </view>
</template>

<script>
import { enumConverter, filterToWhere } from "@/js_sdk/validator/coupons.js";
import { mapGetters } from "vuex";

const db = uniCloud.database();
// 表查询配置
const dbOrderBy = ""; // 排序字段
const dbSearchFields = []; // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
// 分页配置
const pageSize = 20;
const pageCurrent = 1;

const orderByMapping = {
  ascending: "asc",
  descending: "desc",
};

export default {
  data() {
    return {
      query: "",
      where: "",
      orderby: dbOrderBy,
      orderByFieldName: "",
      selectedIndexs: [],
      options: {
        pageSize,
        pageCurrent,
        filterData: {
          discount_data: this.numberRange(1, 99),
          discount_index: null,
          status_localdata: [
            {
              value: 0,
              text: "未发布",
            },
            {
              value: 1,
              text: "已发布",
            },
            {
              value: 2,
              text: "已过期",
            },
          ],
        },
        ...enumConverter,
      },
      imageStyles: {
        width: 64,
        height: 64,
      },
      exportExcel: {
        filename: "coupons.xls",
        type: "xls",
        fields: {
          分类: "category_id",
          user_id: "user_id",
          优惠券名称: "name",
          折扣率: "discount",
          有效期: "validity",
          优惠券状态: "status",
          自定义图片: "customImage",
          创建时间: "create_date",
          最后修改时间: "last_modify_date",
        },
      },
      exportExcelData: [],
    };
  },
  onLoad() {
    this._filter = {};
    // 确保分类数据被加载
    this.$store.dispatch("categories/fetchCategories");
  },
  onReady() {
    this.$refs.udb.loadData();
  },
  computed: {
    ...mapGetters("categories", ["allCategories"]),
    isSuperAdmin() {
      return this.$hasRole("admin");
    },
    collectionList() {
      const userInfo = uni.getStorageSync("uni-id-pages-userInfo");

      return this.$hasRole("admin")
        ? [
            db
              .collection("coupons")
              .field(
                "category_id,user_id,name,discount,validity,status,customImage,create_date,last_modify_date"
              )
              .getTemp(),
            db
              .collection("news-articles-image")
              .field("title as text, _id, category_id as parent_category_id")
              .getTemp(),
          ]
        : [
            db
              .collection("coupons")
              .where({ user_id: userInfo._id })
              .field(
                "category_id,user_id,name,discount,validity,status,customImage,create_date,last_modify_date"
              )
              .getTemp(),
            db
              .collection("news-articles-image")
              .where({ user_id: userInfo._id })
              .field("title as text, _id, category_id as parent_category_id")
              .getTemp(),
          ];
    },
  },
  methods: {
    getCategoryName(item) {
      const { category_id: categoryInfo } = item;

      if (!categoryInfo) return "未分类";
      if (
        Array.isArray(categoryInfo) &&
        categoryInfo[0] &&
        categoryInfo[0]._id
      ) {
        const id =
          item.category_id[0].parent_category_id || item.category_id[0]._id; // 优先使用 parent_category_id，如果不存在则使用 _id
        // 查找分类的 text 字段值，这里假设 allCategories 是一个包含所有分类的数组，每个分类对象都有一个 text 字段，对应分类的名称或标识
        const target = this.allCategories.find(
          (category) => category._id === id
        );
        if (target) {
          return target.text;
        }
      }
      return "未知分类";
    },
    getActivityName(categoryId) {
      // 这里需要添加活动的查询逻辑
      return categoryId || "未关联活动";
    },
    numberRange(start, end) {
      return Array.from({ length: end - start + 1 }, (_, i) => ({
        value: start + i,
        text: `${start + i}%`,
      }));
    },
    onqueryload(data) {
      this.exportExcelData = data;
    },
    getWhere() {
      const query = this.query.trim();
      if (!query) {
        return "";
      }
      const queryRe = new RegExp(query, "i");
      return dbSearchFields
        .map((name) => queryRe + ".test(" + name + ")")
        .join(" || ");
    },
    search() {
      const newWhere = this.getWhere();
      this.where = newWhere;
      this.$nextTick(() => {
        this.loadData();
      });
    },
    loadData(clear = true) {
      this.$refs.udb.loadData({
        clear,
      });
    },
    onPageChanged(e) {
      this.selectedIndexs.length = 0;
      this.$refs.table.clearSelection();
      this.$refs.udb.loadData({
        current: e.current,
      });
    },
    navigateTo(url, clear) {
      // clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
      uni.navigateTo({
        url,
        events: {
          refreshData: () => {
            this.loadData(clear);
          },
        },
      });
    },
    // 多选处理
    selectedItems() {
      var dataList = this.$refs.udb.dataList;
      return this.selectedIndexs.map((i) => dataList[i]._id);
    },
    // 批量删除
    delTable() {
      this.$refs.udb.remove(this.selectedItems(), {
        success: (res) => {
          this.$refs.table.clearSelection();
        },
      });
    },
    // 多选
    selectionChange(e) {
      this.selectedIndexs = e.detail.index;
    },
    confirmDelete(id) {
      this.$refs.udb.remove(id, {
        success: (res) => {
          this.$refs.table.clearSelection();
        },
      });
    },
    sortChange(e, name) {
      this.orderByFieldName = name;
      if (e.order) {
        this.orderby = name + " " + orderByMapping[e.order];
      } else {
        this.orderby = "";
      }
      this.$refs.table.clearSelection();
      this.$nextTick(() => {
        this.$refs.udb.loadData();
      });
    },
    filterChange(e, name) {
      this._filter[name] = {
        type: e.filterType,
        value: e.filter,
      };
      let newWhere = filterToWhere(this._filter, db.command);
      if (Object.keys(newWhere).length) {
        this.where = newWhere;
      } else {
        this.where = "";
      }
      this.$nextTick(() => {
        this.$refs.udb.loadData();
      });
    },
  },
};
</script>

<style></style>
